import { Component, OnInit, EventEmitter, Injector } from '@angular/core';
import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms';
import { FormValidatorService } from "../../core/service/form-validator.service";
import { HttpService } from "../../core/service/http.service";
import { Register } from "../../core/model/Register";
import { HttpRes } from "../../core/model/HttpRes";
import { Router } from "@angular/router";
import { CityListComponent } from '../../system/school/cityList';
import { AuthService } from "../../core/service/auth.service";
import { Login } from "../../core/model/Login";
import { ClassInfoOutput } from "../../core/model/ClassInfoDto";
import { PagerSearchInput, KeyValueOutput, SearchValue } from "../../core/model/CommonDto";
import { NzMessageService } from 'ng-zorro-antd';
import { Observable } from 'rxjs/Observable';
import { debounceTime, switchMap } from 'rxjs/operators';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { NgZorroPageBaseComponent } from '../../core/ng-zorro-page-base-component/ng-zorro-page-base-component.component';
import {
  PagedResultDto, BaseComponentConfig,
  CustomNavigation
} from '../..';
import { SignalRService } from '../../core/service/singnalr-service';
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {

  sign = false;
  schoolName;
  type = 'student';
  typeText = '学号';
  sex = 'male';
  signForm: FormGroup;
  loginForm: FormGroup;
  isSpinning = false;
  isLoading = false;
  cityData; // 市
  provinceData; // 省
  selectedProvince;
  resultxymana;
  resultxy;
  selectedCity;
  collegelName;
  facultydata;
  listEntitiesdata;
  classget;
  aclear;
  collegeDepar;
  classInfo = new Array<KeyValueOutput>();
  searchChange$ = new BehaviorSubject(new SearchValue('', ''));

  constructor(public fb: FormBuilder,
    public FormValidator: FormValidatorService,
    public http: HttpService,
    public router: Router,
    public signalService: SignalRService,
    public Auth: AuthService) {

    const city = new CityListComponent;
    this.cityData = city.cityDatas;
    this.provinceData = city.provinceDatas;
    // 注册表单实例
    this.signForm = this.fb.group({
      personNO: ['', [Validators.required, Validators.minLength(1), Validators.maxLength(30)]],
      personName: ['', [Validators.required, Validators.minLength(1), Validators.maxLength(30)]],
      userName: ['', [Validators.required, Validators.minLength(1), Validators.maxLength(30)]],
      className: ['', [Validators.required, Validators.minLength(1), Validators.maxLength(30)]],
      selectedProvince1: ['', [Validators.required, Validators.minLength(1), Validators.maxLength(30)]],
      selectedCity1: ['', [Validators.required, Validators.minLength(1), Validators.maxLength(30)]],
      schoolName1: ['', [Validators.required, Validators.minLength(1), Validators.maxLength(30)]],
      collegelName1: ['', [Validators.required, Validators.minLength(1), Validators.maxLength(30)]],
      facultydata1: ['', [Validators.required, Validators.minLength(1), Validators.maxLength(30)]],
      passwords: this.fb.group({
        password: ['', [Validators.required, Validators.minLength(1), Validators.maxLength(16)]],
        ensurePassword: ['', [Validators.required, Validators.minLength(1), Validators.maxLength(16)]]
      }, { validator: this.FormValidator.passwordValidator })
    });

    // 登录表单实例
    this.loginForm = this.fb.group({
      name: ['', [Validators.required, Validators.minLength(1), Validators.maxLength(30)]],
      password: ['', [Validators.required, Validators.minLength(1), Validators.maxLength(30)]]
    });

    // this.getClasses();
    const optionList$: Observable<Array<KeyValueOutput>> =
      this.searchChange$.asObservable().pipe(debounceTime(1000)).pipe(
        switchMap((searchValue: SearchValue) => {
          try {
            if (searchValue && searchValue.url) {
              return this.http
                .get<Array<KeyValueOutput>>(`${searchValue.url}?input=${searchValue.value}`).then(e => e);
            } else {
              return new Promise(resolve => {
                resolve(new Array<KeyValueOutput>());
              });
            }
          } catch {
            return new Promise(resolve => {
              resolve(new Array<KeyValueOutput>());
            });
          }

        }));
    optionList$.subscribe(data => {
      this.classInfo = data;
      this.isLoading = false;
    });
    this.searchChange$.next(new SearchValue('', 'ClassInfo/GetClassByName'));
    this.searchChange$.next(new SearchValue('', 'ClassInfo/GetClassByName'));
  }

  onSearch(value: string, url: string): void {
    this.isLoading = true;
    this.searchChange$.next(new SearchValue(value, 'ClassInfo/GetClassByName'));
    this.searchChange$.next(new SearchValue(value, 'ClassInfo/GetClassByName'));
  }

  async onLoginSubmit() {
    if (this.loginForm.valid) {
      this.isSpinning = true;
      try {
        const result = await this.http.post<any>('SystemUser/LoginUser', this.loginForm.value);
        this.Auth.token = result;
        // 注册sockect登陆信息
        this.signalService.startConnection();
        this.signalService.connectionEstablished.subscribe(e => {
          if (e) {
            this.signalService.RgisterUser(this.Auth.token.userid).then(e1 => this.signalService.IniChatContext());
          }
        });
        // 存储身份
        sessionStorage.setItem('userRoleType', this.Auth.token.userRoleType); // 身份
        sessionStorage.setItem('schoolId', this.Auth.token.schoolId); // 学校id
        sessionStorage.setItem('schoolName', this.Auth.token.schoolName); // 学校名称
        sessionStorage.setItem('academeId', this.Auth.token.academeId); // 院id
        sessionStorage.setItem('academeName', this.Auth.token.academeName); // 院名称
        sessionStorage.setItem('collegeDepartmentId', this.Auth.token.collegeDepartmentId); // 系id
        sessionStorage.setItem('collegeDepartmentName', this.Auth.token.collegeDepartmentName); // 系名称
        sessionStorage.setItem('userid', this.Auth.token.userid); // 用户id
        sessionStorage.setItem('userName', this.Auth.token.userName); // 用户名称
        sessionStorage.setItem('loginType', this.Auth.token.loginType);
        sessionStorage.setItem('className', this.Auth.token.className); // 学生登入判定班级
        // 跳转至index页;
        this.router.navigate(['/index']);
      } catch (error) {

      }
      this.isSpinning = false;
    }
  }

  async onSignSubmit() {
    for (const i of Object.keys(this.signForm.controls)) {
      this.signForm.controls[i].markAsDirty();
      this.signForm.controls[i].updateValueAndValidity();
    }
    if (this.signForm.valid) {
      // this.isSpinning = true;
      const registerData = new Register();
      registerData.userPwd = this.signForm.value.passwords.password;
      // registerData.userGender = this.sex === 'male' ? 1 : 0;
      registerData.personName = this.signForm.value.personName;
      registerData.userName = this.signForm.value.userName;
      registerData.personNO = this.signForm.value.personNO;
      // registerData.selectedProvince1 = this.signForm.value.selectedProvince1;
      // registerData.selectedCity1 = this.signForm.value.selectedCity1;
      // registerData.schoolName1 = this.signForm.value.schoolName1;
      // registerData.collegelName1 = this.signForm.value.collegelName1;
      // registerData.facultydata1 = this.signForm.value.facultydata1;
      registerData.classId = parseInt(this.signForm.value.className, 10);
      registerData.isActive = true;
      registerData.base64Photo = "";
      registerData.departmentId = this.collegeDepar;
      registerData.phoneNumber = "";
      registerData.password = "";
      registerData.academeId = 0;
      // registerData.drillProjectIdList = [0];
      // registerData.classinfoIdList = [0];




      const result = this.http.post('SystemUser/StudentRegister', registerData);
      this.isSpinning = false;
      this.toggle();
    }
  }


  ngOnInit() {
  }

  checkType($type) {
    this.type = $type;
    this.typeText = $type === 'teacher' ? '教师编号' : $type === 'admin' ? '管理员账号' : '学号';
  }

  checkSex($sex) {
    this.sex = $sex;
  }

  toggle() {
    this.sign = !this.sign;
  }

  async getClasses() {
    this.classInfo = await this.http.get<Array<KeyValueOutput>>('ClassInfo/GetClassByName?input');
  }

  // 根据省市获取学校
  async citygetschool(e) {
    if (e === undefined) {


    } else {
      const searchName = this.selectedProvince + "-" + e;

      this.listEntitiesdata = await this.http.get<any>(`School/GetSchoolByAddress?address=${searchName}`);


    }
  }

  // 根据学校获取学院
  async provinceChangesol(e) {
    if (e === undefined) {

    } else {
      this.resultxy = await this.http.get<any>(`School/GetAllAcademeBySchool?input=${e}`);
    }

  }
  // 根据学院获取系
  async getmana(e) {
    if (e === undefined) {

    } else {
      const data = { "academeId": e, "collegeDepartmentName": "" };

      this.resultxymana = await this.http.post<any>(`School/GetDepartmentByAcademe`, data);
    }


  }
  // 根据系获取班级
  async facultyget(e) {
    if (e === undefined) {

    } else {
      this.collegeDepar = e;
      const data = { "name": "", cid: e };
      this.classget = await this.http.post<any>(`ClassInfo/GetAllClassinfoDtoZh`, data);
    }
    // this.resultxymana[0].id

  }
  // 学校模糊搜索
  async searchschoolName(searchText: string) {
    const that = this;
    clearTimeout(this.aclear);
    this.aclear = setTimeout(() => {
      that.sealist(searchText);
    }, 1000);
  }
  sealist(i) {
    const datalist = { "Name": i };
    this.listEntitiesdata = [];
    this.http.post<any>("School/GetSchoolToTen", datalist).then(e => {
      this.listEntitiesdata = e;
    });
  }

  // 学院模糊搜索
  async searchcollegelName(searchText: string) {
    const that = this;
    clearTimeout(this.aclear);
    this.aclear = setTimeout(() => {
      that.sealistcollegelName(searchText);
    }, 1000);
  }
  sealistcollegelName(i) {
    const datalist = { "Name": i };
    this.resultxy = [];
    this.http.post<any>("School/GetSchoolToTen", datalist).then(e => {
      this.resultxy = e;
    });
  }

  // 学系模糊搜索
  async searchfacultyget(searchText: string) {
    const that = this;
    clearTimeout(this.aclear);
    this.aclear = setTimeout(() => {
      that.sealistfacultyget(searchText);
    }, 1000);
  }
  sealistfacultyget(i) {
    const datalist = { "Name": i };
    this.resultxymana = [];
    this.http.post<any>("School/GetSchoolToTen", datalist).then(e => {
      this.resultxymana = e;
    });
  }

  // 班级模糊搜索
  async searchclassName(searchText: string) {
    const that = this;
    clearTimeout(this.aclear);
    this.aclear = setTimeout(() => {
      that.sealistclassName(searchText);
    }, 1000);
  }
  sealistclassName(i) {
    const datalist = { "Name": i };
    this.classget = [];
    this.http.post<any>("ClassInfo/GetAllClassInfoByDepartment", datalist).then(e => {
      this.classget = e;
    });
  }

}
